package com.xq.springboot.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Http切面类.
 * 
 * @author 郭凯强
 */
@Aspect
@Component
public class HttpAspect {
	private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

	/**
	 * 定义切入点(AspectJ的切入点语法)
	 */
	@Pointcut("execution(public * com.xq.springboot.controller.GirlController.*(..))")
	public void log() {
	}

	/**
	 * 目标方法执行前
	 * 
	 * @param joinPoint
	 *            连接点(Spring AOP中连接点总是方法调用)
	 */
	@Before("log()")
	public void doBefore(JoinPoint joinPoint) {
		// 获取请求对象
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();

		// url
		logger.info("url={}", request.getRequestURL());

		// method
		logger.info("method={}", request.getMethod());

		// ip
		logger.info("ip={}", request.getRemoteAddr());

		// 类方法
		logger.info("class_method={}",
				joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

		// 参数
		logger.info("args={}", joinPoint.getArgs());
	}

	/**
	 * 目标方法执行后(不管目标方法是否成功执行, 都执行此方法)
	 */
	@After("log()") //after-1
	public void doAfter() {
		logger.info("======================TARGET METHOD FINISHED======================");
	}

	/**
	 * AfterReturning 目标方法成功执行后, 执行此方法
	 * 
	 * @param res
	 *            目标方法(成功)执行后的结果
	 */
	@AfterReturning(returning = "res", pointcut = "log()") //after-2
	public void doAfterReturning(Object res) {
		logger.info("response={}", res.toString());
	}

	@AfterThrowing(throwing = "ex", pointcut = "log()") //after-3
	public void doAfterThrowing(Throwable ex) {
		logger.error("目标方法抛出的异常为={}", ex.getMessage());
	}
}
